function createJsonView(obj) {
    function createElementFromJson(value, isRoot = false) {
        if (value === null) return `<span class="json-null">null</span>`;
        if (typeof value === "string") return `<span class="json-string">"${value}"</span>`;
        if (typeof value === "number") return `<span class="json-number">${value}</span>`;
        if (typeof value === "boolean") return `<span class="json-boolean">${value}</span>`;
        
        if (Array.isArray(value)) {
            if (value.length === 0) return "[]";
            const content = value.map((item, index) => {
                return `
                    <div class="json-array-item">
                        ${createElementFromJson(item)}${index < value.length - 1 ? ',' : ''}
                    </div>`;
            }).join('');
            return `
                <div class="json-array-wrapper">
                    <div class="collapsible">
                        <span class="toggle-btn">▼</span>[
                    </div>
                    <div class="json-array collapsible-content">
                        ${content}
                    </div>
                    <div>]</div>
                </div>`;
        }
        
        if (typeof value === "object") {
            const pairs = Object.entries(value).map(([key, val], index, arr) => {
                return `
                    <div class="json-property">
                        <span class="json-key">"${key}"</span>: 
                        ${createElementFromJson(val)}${index < arr.length - 1 ? ',' : ''}
                    </div>`;
            });
            
            const wrapper = `
                <div class="json-object-wrapper">
                    <div class="collapsible">
                        <span class="toggle-btn">▼</span>${!isRoot ? '{' : ''}
                    </div>
                    <div class="json-object collapsible-content">
                        ${pairs.join('')}
                    </div>
                    <div>${!isRoot ? '}' : ''}</div>
                </div>`;
            return wrapper;
        }
        
        return String(value);
    }
    
    return createElementFromJson(obj, true);
}

async function analyzeComplaint() {
    const complaintText = document.getElementById('complaintText').value;
    const jsonViewer = document.getElementById('jsonViewer');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const analyzeBtn = document.getElementById('analyzeBtn');

    if (!complaintText.trim()) {
        alert('请输入投诉内容');
        return;
    }

    try {
        loadingIndicator.style.display = 'block';
        jsonViewer.innerHTML = '';
        analyzeBtn.disabled = true;

        const response = await fetch('/api/analyze_complaint', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                complaint_text: complaintText
            })
        });

        const result = await response.json();
        
        if (result && result.code === "1") {
            jsonViewer.innerHTML = createJsonView(result.data);
            
            // 添加折叠功能
            document.querySelectorAll('.collapsible').forEach(element => {
                element.addEventListener('click', function(e) {
                    const toggleBtn = this.querySelector('.toggle-btn');
                    const content = this.nextElementSibling;
                    if (content && content.classList.contains('collapsible-content')) {
                        toggleBtn.style.transform = content.classList.contains('hidden') 
                            ? 'rotate(0deg)' 
                            : 'rotate(-90deg)';
                        content.classList.toggle('hidden');
                    }
                });
            });
        } else {
            jsonViewer.innerHTML = `<div class="error">处理失败：${result.message || '请求失败'}</div>`;
        }
    } catch (error) {
        jsonViewer.innerHTML = `<div class="error">发生错误：${error.message}</div>`;
    } finally {
        loadingIndicator.style.display = 'none';
        analyzeBtn.disabled = false;
    }
}

// 初始化页面时添加事件监听器
document.addEventListener('DOMContentLoaded', () => {
    // 添加回车键提交功能
    document.getElementById('complaintText').addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            analyzeComplaint();
        }
    });
}); 